import Fixed from "./_fixed.vue";

var elArr = [];

function rxFixed({
  el,//容器
  event,//事件
  placement,
  propsData,
  store
}, component) {

  var resolve,
    reject,
    promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    })

  if (elArr.indexOf(el) === -1) {

    var newEl = document.createElement('div')
    el.appendChild(newEl);
    propsData||(propsData={})
    var vm = new Vue({
      el:newEl,
      template: `<Fixed ref="fixed" @reject="reject" :placement="placement">
                  <com-content @resolve="resolve" @reject="reject" ${Object.keys(propsData).map(k => `
                  :${k}="${k}"\s
                `).join('')} />
                </Fixed>`,
      store,
      data() {
        return {
          placement: placement || 'bottom-start',
          ...propsData
        };
      },
      components: {
        Fixed,
        'com-content': component
      },
      mounted() {
        var _this=this;
        el.fixedDestory=function(){
          elArr.remove(el)
          _this.$destroy()
          _this.$el.remove()
        }
        elArr.push(el);
        this.$refs.fixed.show(el, event)
      },
      methods: {
        resolve(arg) {
          resolve(arg);
          elArr.remove(el)
          this.$destroy()
          this.$el.remove()

        },
        reject() {
          reject();
          elArr.remove(el)
          this.$destroy()
          this.$el.remove()

        }
      }
    });
  }else{
    el.fixedDestory();
    delete el.fixedDestory;
  }

  return promise;
}

export default rxFixed
